import json
import re
import random

from django.core.cache import cache
from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import viewsets

from .models import UserModel
from django.db.models import Q
from jwtool import jwt_tool
from sendsms import send_message
from coderedis import codeRedis
from .task import send_sms_task

class LoginViewSet(viewsets.ModelViewSet):
    # 账号密码登录(账号：手机号、用户名、邮箱)
    @action(methods=['POST'], detail=False,url_name="login")
    def login(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        query = Q(username=account) | Q(phone=account) | Q(email=account)
        userInfo = UserModel.objects.filter(query).first()
        # 检测账号密码
        if not userInfo:
            return Response({
                "code": 400,
                "msg": "用户不存在"
            }, status=400)
        if userInfo.password != password:
            return Response({
                "code": 400,
                "msg": "密码错误"
            }, status=400)
        # 生成token
        token = jwt_tool.get_token(userInfo.id)
        return Response({
            "code": 200,
            "msg": "登录成功",
            "data": {
                "token": token,
                "username": userInfo.username,
                "id": userInfo.id
            }
        })

    # 定义发送验证码接口
    @action(methods=['POST'], detail=False)
    def send_code(self, request):
        phone = request.data.get('phone')
        if not re.compile(r'^1[3-9]\d{9}$').match(phone):
            return Response({
                "code": 400,
                "message": "手机号格式不对！",
                "data": {}
            }, status=400)
        # 检测验证码发送频率
        interval = codeRedis.getCodeInterval(phone)
        # if interval != -2:
        #     return Response({
        #         "code": 400,
        #         "message": "验证码发送频率过高！",
        #         "data": {}
        #     }, status=400)
        # 生成验证码
        code = str(random.randint(1000, 9999))
        # 发送验证码
        # codeRes = send_message(phone,code)
        task = send_sms_task.delay(phone,code)
        codeRes = task.get()
        print("返回结果是：",codeRes)

        # 检查发送结果
        if codeRes["statusCode"] == "000000":
            codeRedis.setCode(phone,code)
            return Response({
                "code": 200,
                "message": "发送成功",
                "data": {"code": code}
            })
        else:
            return Response({
                "code": 400,
                "message": "发送失败,请稍后重试！",
                "data": {}
            }, status=400)

    # 定义手机号登录接口
    @action(methods=['POST'], detail=False)
    def phone_login(self, request):
        phone = request.data.get('phone')
        code = request.data.get('code')
        # 验证手机号格式
        if not re.compile(r'^1[3-9]\d{9}$').match(phone):
            return Response({
                "code": 400,
                "message": "手机号格式不对！",
                "data": {}
            }, status=400)
        # 检测验证码是否过期
        if codeRedis.getCode(phone) is None:
            return Response({
                "code": 400,
                "message": "验证码已过期",
                "data": {}
            }, status=400)
        # 检测验证码输入是否正确
        if codeRedis.getCode(phone) != str(code):
            return Response({
                "code": 400,
                "message": "验证码输入错误",
                "data": {}
            }, status=400)
        user = UserModel.objects.filter(phone=phone).first()
        # 如果手机号不存在就注册反之就返回
        if not user:
            user = UserModel.objects.create(phone=phone)
            user.username = phone
            user.save()
        # 生成token
        token = jwt_tool.get_token(user.id)
        # 返回用户信息
        return Response({
            "code": 200,
            "message": "登录成功",
            "data": {
                "token": token,
                "id": user.id
            }
        })
